<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 添加按钮和搜索框部分 -->
        <el-row type="flex" justify="space-between">
          <el-col>
            <el-button type="primary" size="small" @click="addcategory">添加分类</el-button>
          </el-col>
          <el-row type="flex" justify="end">
            <el-col>
              <el-input v-model="title_contains" placeholder="请输入内容" style="width:600px" />
            </el-col>
            <el-col>
              <el-button icon="el-icon-search" type="info" plain @click="searchFn" />
            </el-col>
          </el-row>
        </el-row>
        <el-divider />
        <!-- 表格 -->
        <el-table
          :data="categoryList"
          border
          style="width: 100%"
          height="calc(100vh - 280px)"
        >
          <el-table-column
            prop="image"
            label="图片"
            width="300px"
          >
            <template #default="{row}">
              <img :src="row.image" alt="">
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            label="标题"
            width="300"
          />
          <el-table-column
            prop="desc"
            label="介绍"
          />
          <el-table-column
            label="操作"
            width="300px"
          >
            <template #default="{row}">
              <el-button type="primary" size="small" @click="editcategoryList(row.id)">编辑</el-button>
              <el-button type="danger" size="small" @click="delcategoryList(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-divider />
        <el-row type="flex" justify="center" style="margin-top:10px">
          <!-- 分页 -->
          <pagination ref="pagination" :obj="pageConfig" :total="total" @currentChange="currentChang" @sizeChange="sizeChang" />
        </el-row>
      </el-card>
      <!-- 弹框 -->
      <el-dialog :title="formData.id?'编辑分类':'新增分类'" :visible="isShowDialog" @close="btnCanel">
        <!-- :label-position="labelPosition"这个属性代表标签在输入框的哪个位置 -->
        <el-form ref="addForm" :label-position="labelPosition" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="formData.desc" placeholder="请输入描述" type="textarea" />
          </el-form-item>
          <el-form-item label="上传图片">
            <!-- remove是删除图片
            http-request是指让本地图片不通过action上传
            change是本地图片上传后，上传组件隐藏 -->
            <uploadimage ref="cateImage" />
          </el-form-item>
        </el-form>
        <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
        <el-row slot="footer" type="flex" justify="end">
          <!-- 列被分为24 -->
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnOK">确定</el-button>
            <el-button size="small" @click="btnCanel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import uploadimage from '../../components/uploadImage/index'
import { getCategory, delcategory, addcategory, editcategory, editsavecategory, getCategoryCount } from '../../api/category'
export default {
  components: { uploadimage },
  data() {
    return {
      pageConfig: {
        _start: 0,
        _limit: 2,
        title_contains: ''
      },
      title_contains: '',
      total: 0,
      // 声明分类数据的变量
      categoryList: [],
      isShowDialog: false,
      labelPosition: 'top',
      formData: {},
      rules: {
        title: [
          { required: true, message: '请输入标题名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用接口
    this.getcate()
    this.getgory()
  },
  methods: {
    // 获取分类数据的列表,发送请求
    getcate() {
      getCategory(this.pageConfig).then((res) => {
        console.log('category', res)
        this.categoryList = res.data
      })
    },
    // 获取数据总数
    async getgory() {
      const { data } = await getCategoryCount()
      const res1 = await getCategory({ ...this.pageConfig, _limit: data, _start: 0 })
      this.total = res1.data.length

      console.log(144, this.total)
    },
    // 删除
    async delcategoryList(id) {
      // try{ 要写的函数 }catch(err){console.log(err);} //这样处理就不会出现报错
      try {
        // 二次提示
        await this.$confirm('确定删除数据？')
        // 发送请求
        await delcategory(id)
        // 提示用户
        this.$message.success('删除成功')
        // 删除数据后，页面分页减少 ,排除只有一页数据的情况
        if (this.categoryList.length === 1 && this.$refs.pagination.currentPage !== 1) {
        // 删除后得到的总页数=总页数-一页显示的总条数
          this.pageConfig._start = this.pageConfig._start - this.pageConfig._limit
          this.$refs.pagination.currentPage--
          this.getgory()
        }
        // 更新页面
        this.getcate()
      } catch (err) {
        console.log(err)
      }
    },
    addcategory() {
      this.isShowDialog = true
    },
    async  editcategoryList(id) {
      // 弹框
      this.isShowDialog = true
      // 回显
      const res = await editcategory(id)
      this.formData = res.data
      // 回显图片
      if (this.formData.image) {
        this.$refs.cateImage.fileList = [
          {
            url: this.formData.image
          }
        ]
      }
    },
    async  btnOK() {
      // 校验
      await this.$refs.addForm.validate()
      // 输入内容后保存数据
      if (this.formData.id) {
        // searchMixin() 混入方法 解决筛选再新增/编辑的问题
        const msg = [this.formData.title]
        console.log('this.formData.title', this.formData.title)
        const arr = this.searchMixin('', this.pageConfig.title_contains, msg)
        this.pageConfig.title_contains = arr[1]
        console.log('this.pageConfig', this.pageConfig)
        // 发送修改编辑保存数据的请求
        await editsavecategory({
          ...this.formData,
          // 如果有图片要保存，要拼接，然后发到后台
          image: this.$refs.cateImage.fileList[0].url
        })
      } else {
        // searchMixin() 混入方法 解决筛选再新增/编辑的问题
        const msg = [this.formData.title]
        console.log('this.formData.title', this.formData.title)
        const arr = this.searchMixin('', this.pageConfig.title_contains, msg)
        this.pageConfig.title_contains = arr[1]
        console.log('this.pageConfig', this.pageConfig)
        // 发送新增数据的请求
        await addcategory({
          ...this.formData,
          // 如果有图片要保存，要拼接，然后发到后台
          image: this.$refs.cateImage.fileList[0].url
        })
      }
      // 提示用户
      this.$message.success('操作成功')
      // 刷新页面
      this.getcate()
      // 刷新分页
      this.getgory()
      // 关闭弹框
      this.isShowDialog = false
    },
    btnCanel() {
      // 清除校验
      this.$refs.addForm.resetFields()
      // 清理数据
      this.formData = {}
      this.$refs.cateImage.fileList = []
      // 关闭弹框
      this.isShowDialog = false
    },
    // 分页点击
    currentChang(page, oldPage) {
      // 计算 _start 改变请求响应的数据
      this.pageConfig._start = (page - oldPage) * this.pageConfig._limit + this.pageConfig._start
      this.getcate()
      this.getgory()
    },
    // 每页显示条数变化
    sizeChang(val) {
      // 改变每页显示的数量
      this.pageConfig._limit = val
      // 数据从第一条开始显示
      this.pageConfig._start = 0
      this.getcate()
      this.getgory()
    },
    // 搜索数据
    searchFn() {
      this.pageConfig._start = 0
      this.$refs.pagination.currentPage = 1
      this.pageConfig.title_contains = this.title_contains
      this.getcate()
      this.getgory()
    }
  }
}
</script>

<style lang="scss" scoped>
//上传图片，当有图片的时候，将上传组件隐藏，反之显示
.disable{
  ::v-deep .el-upload--picture-card{
  display: none;
}
}
img{
   width: 180px;
   height: 180px;
}

</style>
